package com.atguigu.test;

/**
 * 二分查找
 * 前提：数组有序
 */
public class BinarySearch {
    //二分查找的递归实现
    public static int binarySearchRecursive(int[] array, int target, int left, int right) {
        if (left > right) {
            return -1;//数组为空，表示找不到
        }
        int mid = left + (right - left) / 2;//防止（left+right）直接相加导致的整数溢出
        if(array[mid] == target){
            return mid;
        } else if (array[mid]<target) {
            return binarySearchRecursive(array,target,mid+1,right);//在右半部分继续查找
        }else {
            return binarySearchRecursive(array,target,left,mid-1);//在左半部分继续查找
        }
    }
    //二分查找的迭代实现
    public static int binarySearchIterative(int[] array,int target){
        int left = 0;
        int right = array.length-1;

        while (left<=right){
            int mid = left + (right-left)/2;
            if(array[mid] == target){
                return mid;
            } else if (array[mid]<target) {
                left = mid + 1;
            }else {
                right = mid -1;
            }
        }
        return -1;//数组为空，表示找不到
    }

    public static void main(String[] args) {
        int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 7;
        int resultRecursive = binarySearchRecursive(sortedArray,target,0,sortedArray.length-1);
        System.out.println("递归查找结果："+(resultRecursive != -1 ? "找到元素，索引为："+resultRecursive:"未找到元素"));

        int resultIterative = binarySearchIterative(sortedArray,target);
        System.out.println("迭代查找结果："+(resultRecursive != -1 ? "找到元素，索引为："+resultIterative:"未找到元素"));
    }
}
